package com.example.jisuanji5;

import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    protected StringBuffer expressionString;
//    List<String> historyRecord=new ArrayList<String>();
    private int statusCode=0;
    private int click;
//    private long exitTime;
    //用来控制用户点击是否按两次离开计算器
    AlertDialog builder = null;
    Button btn_0;                   //数字按钮
    Button btn_1;
    Button btn_2;
    Button btn_3;
    Button btn_4;
    Button btn_5;
    Button btn_6;
    Button btn_7;
    Button btn_8;
    Button btn_9;
    Button btn_equal;            //运算符按钮
    Button btn_add;
    Button btn_minus;
    Button btn_mul;
    Button btn_divide;
    Button btn_point;               //小数点按钮
    Button btn_delete;
    Button btn_clear;
    Button btn_sin;
    Button btn_cos;
    Button btn_tan;
    Button btn_log;
    Button btn_sqrt;
    Button btn_exp;
    Button btn_LB;
    Button btn_RB;
    EditText et_input;
    private SoundPool mySoundPool;
//    boolean clear_flag;  //清空标识

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        expressionString = new StringBuffer("");
//        mySoundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);

        btn_0 = (Button) findViewById(R.id.btn_0);
        btn_1 = (Button) findViewById(R.id.btn_1);
        btn_2 = (Button) findViewById(R.id.btn_2);
        btn_3 = (Button) findViewById(R.id.btn_3);
        btn_4 = (Button) findViewById(R.id.btn_4);
        btn_5 = (Button) findViewById(R.id.btn_5);
        btn_6 = (Button) findViewById(R.id.btn_6);
        btn_7 = (Button) findViewById(R.id.btn_7);
        btn_8 = (Button) findViewById(R.id.btn_8);
        btn_9 = (Button) findViewById(R.id.btn_9);

        btn_point = (Button) findViewById(R.id.btn_point);
        btn_add = (Button) findViewById(R.id.btn_add);
        btn_clear = (Button) findViewById(R.id.btn_clear);
        btn_delete = (Button) findViewById(R.id.btn_delete);
        btn_divide = (Button) findViewById(R.id.btn_divide);
        btn_equal = (Button) findViewById(R.id.btn_equal);
        btn_minus = (Button) findViewById(R.id.btn_minus);
        btn_mul = (Button) findViewById(R.id.btn_mul);      //实例化按钮

        btn_sin = (Button) findViewById(R.id.btn_sin);
        btn_cos = (Button) findViewById(R.id.btn_cos);
        btn_tan = (Button) findViewById(R.id.btn_tan);
        btn_log = (Button) findViewById(R.id.btn_log);
        btn_sqrt = (Button) findViewById(R.id.btn_sqrt);
        btn_exp = (Button) findViewById(R.id.btn_exp);

        btn_RB = (Button) findViewById(R.id.btn_RB);
        btn_LB = (Button) findViewById(R.id.btn_LB);

        et_input = (EditText) findViewById(R.id.et_input);          //实例化显示屏

        btn_0.setOnClickListener(this);      //设置按钮的点击事件
        btn_1.setOnClickListener(this);
        btn_2.setOnClickListener(this);
        btn_3.setOnClickListener(this);
        btn_4.setOnClickListener(this);
        btn_5.setOnClickListener(this);
        btn_6.setOnClickListener(this);
        btn_7.setOnClickListener(this);
        btn_8.setOnClickListener(this);
        btn_9.setOnClickListener(this);
        btn_point.setOnClickListener(this);
        btn_add.setOnClickListener(this);
        btn_clear.setOnClickListener(this);
        btn_divide.setOnClickListener(this);
        btn_delete.setOnClickListener(this);
        btn_equal.setOnClickListener(this);
        btn_mul.setOnClickListener(this);
        btn_minus.setOnClickListener(this);

        btn_sin.setOnClickListener(this);
        btn_cos.setOnClickListener(this);
        btn_tan.setOnClickListener(this);
        btn_log.setOnClickListener(this);
        btn_LB.setOnClickListener(this);
        btn_RB.setOnClickListener(this);
        btn_exp.setOnClickListener(this);
        btn_sqrt.setOnClickListener(this);
    }

    //正则表达式
    public boolean judgeExceptionString() {
        String pattren = "[0-9]\\(|\\)[0-9]";
        Pattern rPattern = Pattern.compile(pattren);
        Matcher matcher = rPattern.matcher(expressionString);
        if(matcher.find()) {
            return false;
        }
        return true;
    }

//    private void playSound(){
//        mySoundPool.play(click, 1, 1, 0, 0, 1);
//    }

    @Override
    public void onClick(View v) {                   //设置触发器
//        playSound();

        if(statusCode == 1 && v.getId() != R.id.btn_clear) {
            Toast.makeText(this, "运算结束，自动清空表达式\n", Toast.LENGTH_SHORT).show();
            expressionString.delete(0, expressionString.length());
            statusCode = 0;
        }
        else{
            switch (v.getId()) {
                case R.id.btn_0:
                    expressionString.append('0');
                    break;
                case R.id.btn_1:
                    expressionString.append('1');
                    break;
                case R.id.btn_2:
                    expressionString.append('2');
                    break;
                case R.id.btn_3:
                    expressionString.append('3');
                    break;
                case R.id.btn_4:
                    expressionString.append('4');
                    break;
                case R.id.btn_5:
                    expressionString.append('5');
                    break;
                case R.id.btn_6:
                    expressionString.append('6');
                    break;
                case R.id.btn_7:
                    expressionString.append('7');
                    break;
                case R.id.btn_8:
                    expressionString.append('8');
                    break;
                case R.id.btn_9:
                    expressionString.append('9');
                    break;
                case R.id.btn_point:
                    expressionString.append('.');
                    break;
                case R.id.btn_add:
                    expressionString.append('+');
                    break;
                case R.id.btn_minus:
                    expressionString.append('-');
                    break;
                case R.id.btn_mul:
                    expressionString.append('*');
                    break;
                case R.id.btn_divide:
                    expressionString.append('/');
                    break;
                case R.id.btn_LB:
                    expressionString.append('(');
                    break;
                case R.id.btn_RB:
                    expressionString.append(')');
                    break;
                case R.id.btn_sin:
                    expressionString.append('s');
                    expressionString.append('i');
                    expressionString.append('n');
                    break;
                case R.id.btn_cos:
                    expressionString.append('c');
                    expressionString.append('o');
                    expressionString.append('s');
                    break;
                case R.id.btn_tan:
                    expressionString.append('t');
                    expressionString.append('a');
                    expressionString.append('n');
                    break;
                case R.id.btn_log:
                    expressionString.append('l');
                    expressionString.append('o');
                    expressionString.append('g');
                    break;
                case R.id.btn_exp:
                    expressionString.append('e');
                    expressionString.append('x');
                    expressionString.append('p');
                    break;
                case R.id.btn_sqrt:
                    expressionString.append('s');
                    expressionString.append('q');
                    expressionString.append('r');
                    expressionString.append('t');
                    break;
                case R.id.btn_delete:
                    if (expressionString.length() - 1 >= 0)
                        expressionString.delete(expressionString.length() - 1, expressionString.length());
                    break;
                case R.id.btn_clear:
                    if (statusCode == 1)
                        statusCode = 0;
                    expressionString.delete(0, expressionString.length());
                    break;
                case R.id.btn_equal:
                    try {
                        if(expressionString.toString().contains("sin")){
                            StringBuffer temp_buffer = expressionString.delete(0,3);
                            Double ans_temp = Double.parseDouble(temp_buffer.toString());
                            Log.d("Tag","value:"+ans_temp);
                            Double ans = Math.sin(ans_temp);
                            expressionString.append('=');
                            expressionString.append(ans);

                        }
                        if(expressionString.toString().contains("cos")){
                            StringBuffer temp_buffer = expressionString.delete(0,3);
                            Double ans_temp = Double.parseDouble(temp_buffer.toString());
                            Log.d("Tag","value:"+ans_temp);
                            Double ans = Math.cos(ans_temp);
                            expressionString.append('=');
                            expressionString.append(ans);
                        }
                        if(expressionString.toString().contains("tan")){
                            StringBuffer temp_buffer = expressionString.delete(0,3);
                            Double ans_temp = Double.parseDouble(temp_buffer.toString());
                            Log.d("Tag","value:"+ans_temp);
                            Double ans = Math.tan(ans_temp);
                            expressionString.append('=');
                            expressionString.append(ans);

                        }
                        if(expressionString.toString().contains("log")){
                            StringBuffer temp_buffer = expressionString.delete(0,3);
                            Double ans_temp = Double.parseDouble(temp_buffer.toString());
                            Log.d("Tag","value:"+ans_temp);
                            Double ans = Math.log(ans_temp);
                            expressionString.append('=');
                            expressionString.append(ans);

                        }
                        if(expressionString.toString().contains("sqrt")){
                            StringBuffer temp_buffer = expressionString.delete(0,4);
                            Double ans_temp = Double.parseDouble(temp_buffer.toString());
                            Log.d("Tag","value:"+ans_temp);
                            Double ans = Math.sqrt(ans_temp);
                            Log.d("tag","value:"+ans);
                            expressionString.append('=');
                            expressionString.delete(0,expressionString.length());
                            Log.d("tag","value:"+expressionString);
                            expressionString.append(ans);
                            Log.d("tag","value:"+expressionString);
                        }
                        if(expressionString.toString().contains("exp")){
                            StringBuffer temp_buffer = expressionString.delete(0,3);
                            Double ans_temp = Double.parseDouble(temp_buffer.toString());
                            Log.d("Tag","value:"+ans_temp);
                            Double ans = Math.exp(ans_temp);
                            expressionString.append('=');
                            expressionString.append(ans);
                            et_input.setText(String.valueOf(ans));
                        }
                        if (judgeExceptionString()) {
                            Calculator calculator = new Calculator();
                            double ans = calculator.calculate(expressionString.toString());
                            expressionString.append('=');
                            expressionString.append(ans);
                            statusCode = 1;
                        } else {
                            statusCode = -1;
                            Toast.makeText(this, "表达式有误，请仔细检查\n输入表达式有歧义", Toast.LENGTH_SHORT).show();
                        }
                    } catch (ArithmeticException e) {
                        statusCode = -1;
                        Toast.makeText(this, "表达式有误，请仔细检查\n除数不能为0", Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        statusCode = -1;
                        Toast.makeText(this, "表达式有误，请仔细检查\n表达式不合法", Toast.LENGTH_SHORT).show();
                    }
                    break;
                default:
                    break;
            }
        }
        et_input.setText(expressionString);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.help:
                Intent intent1 = new Intent(MainActivity.this,help.class);
                startActivity(intent1);
                break;
            case R.id.conversion:
                Intent intent3 = new Intent(MainActivity.this,conversion.class);
                startActivity(intent3);
                break;
            case R.id.transition:
                Intent intent = new Intent(MainActivity.this,transition.class);
                startActivity(intent);
                break;

        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
                if(keyCode == KeyEvent.KEYCODE_BACK){
            builder = new AlertDialog.Builder(MainActivity.this)
                    .setTitle("温馨提示：")
                    .setMessage("您是否要退出计算器？")
                    .setPositiveButton("去意已决",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int whichButton) {
                                    MainActivity.this.finish();
                                }
                            })
                    .setNegativeButton("再留一会~", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    builder.dismiss();
                                }
                            }).show();
                }
        return true;
    }

}